<template>
  <div>
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
        @onMaxLength="onMaxLength"
      />
    </div>
    <div>
      <el-button @click="setContent">设置内容</el-button>
      <el-button @click="getContent">获取内容</el-button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default Vue.extend({
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: '<p>hello123</p>',
      //   工具栏配置
      toolbarConfig: {
        // toolbarKeys: ['bold', '|'],
        excludeKeys: ['italic'],
      },
      //   编辑器配置
      editorConfig: {
        placeholder: '请输入内容...',
        readOnly: false,
        maxLength: 20,
        MENU_CONF: {
          lineHeight: ['1', '1.5', '2', '2.5', '3.5'],
          uploadImage: {
            server: this.$API + '/upload',
            fieldName: 'file',
            maxFileSize: 2 * 1024 * 1024, // 2m
            maxNumberOfFiles: 3,
            allowedFileTypes: ['image/*'],
            headers: {
              token: this.$store.state.token,
            },
            onBeforeUpload(file) {
              console.log('上传之前')
              return file
            },
            onSuccess(file, res) {
              console.log(`${file.name} 上传成功`, res)
            },
            onError(file, err, res) {
              console.log(`${file.name} 上传出错`, err, res)
            },
            customInsert(res, insertFn) {
              console.log('customInsert', res)
              let { path } = res
              path = this.$API + '/' + path
              insertFn(path)
            },
          },
        },
      },
      mode: 'default', // or 'simple'
    }
  },
  methods: {
    onMaxLength(editor) {
      console.log('超过20个', editor)
      //   editor.clear() 清空编辑器
    },
    // 获取内容
    getContent() {
      console.log(this.editor.getHtml())
    },
    // 设置内容
    setContent() {
      this.editor.setHtml('<h1>王祖<b>蓝</b></h1>')
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // 查看所有的配置key
      //   console.log(this.editor.getAllMenuKeys())
    },
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
})
</script>

<style lang="scss" scoped></style>
